using B.S.XZYData.Api.Wrter.Application.Command.WorkReport;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
// ADD ALIAS FOR ENTITY TYPES TO AVOID NAMESPACE COLLISION
using DomainWorkReport = B.S.XZYData.Domain.ZSH.WorkReport;
using DomainWorkReportDefectiveItem = B.S.XZYData.Domain.ZSH.WorkReportDefectiveItem;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System;

namespace B.S.XZYData.Api.Wrter.Application.Handler.WorkReport
{
	/// <summary>
	/// 批量删除报工处理器（伪删除）
	/// </summary>
	public class DeleteWorkReportBatchHandler : IRequestHandler<DeleteWorkReportBatchCommand, ApiResult<int>>
	{
		private readonly IBaseRepository<DomainWorkReport> _workReportRepo;
		private readonly IBaseRepository<DomainWorkReportDefectiveItem> _defectiveItemRepo;

		public DeleteWorkReportBatchHandler(
			IBaseRepository<DomainWorkReport> workReportRepo,
			IBaseRepository<DomainWorkReportDefectiveItem> defectiveItemRepo)
		{
			_workReportRepo = workReportRepo;
			_defectiveItemRepo = defectiveItemRepo;
		}

		public async Task<ApiResult<int>> Handle(DeleteWorkReportBatchCommand request, CancellationToken cancellationToken)
		{
			var res = new ApiResult<int>();
			
			if (request.Ids == null || request.Ids.Count == 0)
			{
				res.Code = ApiEnum.Fail;
				res.Msg = "请选择要删除的报工数据";
				return await Task.FromResult(res);
			}

			try
			{
				// 查询要删除的报工记录
				var workReports = _workReportRepo.GetAll()
					.Where(x => request.Ids.Contains(x.Id) && !x.IsDeleted)
					.ToList();

				if (workReports.Count == 0)
				{
					res.Code = ApiEnum.Fail;
					res.Msg = "未找到要删除的报工数据";
					return res;
				}

				// 同时删除关联的不良品项记录
				var defectiveItems = _defectiveItemRepo.GetAll()
					.Where(x => request.Ids.Contains(x.WorkReportId) && !x.IsDeleted)
					.ToList();

				// 批量伪删除报工记录
				foreach (var item in workReports)
				{
					item.IsDeleted = true;
					item.ModifyTime = DateTime.Now;
					// 注：这里可以根据实际需求设置ModifierId
				}

				// 批量伪删除不良品项记录
				foreach (var item in defectiveItems)
				{
					item.IsDeleted = true;
					item.ModifyTime = DateTime.Now;
					// 注：这里可以根据实际需求设置ModifierId
				}

				// 更新报工记录
				var workReportCount = await _workReportRepo.UpdateBatchAsync(workReports);
				
				// 更新不良品项记录
				if (defectiveItems.Count > 0)
				{
					await _defectiveItemRepo.UpdateBatchAsync(defectiveItems);
				}

				res.Code = ApiEnum.Success;
				res.Msg = $"成功删除 {workReportCount} 条报工记录";
				res.Data = workReportCount;
				return res;
			}
			catch (Exception ex)
			{
				res.Code = ApiEnum.Fail;
				res.Msg = $"删除失败：{ex.Message}";
				return res;
			}
		}
	}
} 